/**
 * 
 */
package com.idea.zd.sys.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yzz
 * @create 2016年4月9日 上午10:39:37
 *  映射数据库，自动生成Entity
 * @author WWF
 */
public class CreateModel {

	private static Connection conn = null;
	private static final String URL;
	private static final String JDBC_DRIVER;
	private static final String USER_NAME;
	private static final String PASSWORD;
	private static final String DATABASENAME;
	private static final String PACKAGENAME;
	private static final String FILE_PATH;
	static {
		/*DATABASENAME = "数据库名";
		URL = "jdbc:postgresql://localhost:5432/" + DATABASENAME;
		JDBC_DRIVER = "org.postgresql.Driver";
		USER_NAME = "数据库帐号";
		PASSWORD = "密码";
		PACKAGENAME = "导入包路径";*/
		FILE_PATH = "main/java/com/idea/zd/kol/model";
		DATABASENAME = "kol_db";
		URL = "jdbc:mysql://120.26.127.134:3306/" + DATABASENAME;
		JDBC_DRIVER = "com.mysql.jdbc.Driver";
		USER_NAME = "root";
		PASSWORD = "admin0099";
		PACKAGENAME = "com.idea.zd.kol.model";
	}

	/**
	 * 获得连接
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		try {
			Class.forName(JDBC_DRIVER);
			conn = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 关闭数据库
	 */
	public static void closeConnection() {
		try {
			if (conn != null && !conn.isClosed()) {
				conn.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 生成字段静态声明
	 * 
	 * @param connection
	 * @param tableName
	 * @return
	 */
	private static String CreateEntityString(String tableName) {
		String result = "package " + PACKAGENAME + ";\n\n";
		result += "import com.jfinal.ext.plugin.tablebind.TableBind; \n";
		result += "import com.jfinal.plugin.activerecord.Model; \n\n";
		
		String sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_KEY='PRI' AND table_name='"
				+ tableName + "';";
		String pkName = "";
		try {
			Statement statement = conn.createStatement();
			ResultSet resultSet = statement.executeQuery(sql);
			while (resultSet.next()) {
				if (resultSet.getString(1) != null
						&& !resultSet.getString(1).isEmpty()) {
					pkName = resultSet.getString(1);
				}
			}
			resultSet.close();
			statement.close();
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		
		
		
		result += "@TableBind(tableName = \""+tableName+"\",pkName=\""+pkName+"\")\n";
		result += "public class "
				+ toLowerCaseTheFristChar(tableName)
				+ " extends Model<"
				+ toLowerCaseTheFristChar(tableName) + ">{\n\n";
		result += "    private static final long serialVersionUID = 1L;\n"/*;
		result += "    public static final "
				+ toLowerCaseTheFristChar(tableName) + " dao = new "
				+ toLowerCaseTheFristChar(tableName) + "();\n\n"*/
		        +"}";
		//result += "    /**表名**/ \n";
		//result += "    public static String TABLE = \"" + tableName + "\";";
		
		
		return result;
		
		//String sql = "select column_name from information_schema.columns where table_name = '"
				//+ tableName + "';";
		//try {
			//Statement statement = conn.createStatement();
			//ResultSet resultSet = statement.executeQuery(sql);
			//while (resultSet.next()) {
				//if (resultSet.getString(1) != null
					//	&& !resultSet.getString(1).isEmpty()) {
					//String string = resultSet.getString(1);
					//String row = "    public static final String "
					//		+ string.toUpperCase(Locale.CHINA) + " = \""
					//		+ string + "\";";
					//String note = "    /****/";
					//result += "\n" + note + "\n" + row;
				//}
			//}
			//resultSet.close();
			//statement.close();
			//result += "\n }";
			//return result;
		//} catch (SQLException e) {
			//e.printStackTrace();
			//return null;
		//}
	}

	/**
	 * 获得数据库的所有表名
	 * 
	 * @return
	 */
	public static List<String> getAllTables() {
		String sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '"+DATABASENAME+"'";
		try {
			List<String> result = new ArrayList<String>();
			Statement statement = conn.createStatement();
			ResultSet resultSet = statement.executeQuery(sql);
			while (resultSet.next()) {
				if (resultSet.getString(1) != null
						&& !resultSet.getString(1).isEmpty()) {
					result.add(resultSet.getString(1));
				}
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 生成Entity
	 */
	public static void CreateEntity() {
		try {
			getConnection();
			List<String> tables = getAllTables();
			for (int i = 0; i < tables.size(); i++) {
				File createFolder = new File(System.getProperty("user.dir")
						+ "/src/" + FILE_PATH.replace(".", "/"));
				// 路径不存在，生成文件夹
				if (!createFolder.exists()) {
					createFolder.mkdirs();
				}
				String entityString = CreateEntityString(tables.get(i).trim());
				File entity = new File(createFolder.getAbsolutePath() + "/"
						+ toLowerCaseTheFristChar(tables.get(i))
						+ ".java");
				if (!entity.exists()) {
					// 写入文件
					BufferedWriter out = new BufferedWriter(new FileWriter(
							entity, true));
					out.write(entityString);
					out.close();
					out = null;
					entity = null;
				}
			}
			closeConnection();
			System.out.println("生成成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		CreateEntity();
		//System.out.println(mpl(5));
	}
	
	static int mpl(int c){
		if(c==1||c==0)
		return c;
		else
		return c*mpl(c-1);
	}
	
	private static String toLowerCaseTheFristChar(String str){
			StringBuffer sb = new StringBuffer();
			
			if(str.indexOf("_") > -1){
				str = str.substring(str.indexOf("_")+1,str.length());
			}
			
			if(str!=null){
				
				for(int i=0;i<str.length();i++){
					char c = str.charAt(i);
					
					if(i == 0){
						sb.append(Character.toUpperCase(c));
					}else if(c == '_'){
						++i;
						c = str.charAt(i);
						sb.append(Character.toUpperCase(c));
					}else{
					
						sb.append(Character.toLowerCase(c));
					}
				}
			}
			
			return sb.toString();
	}

}
